package com.ocom.human.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.HumanServiceUrl;
import com.ocom.common.dto.EditMngUserFormDto;
import com.ocom.common.dto.GetMngUserFormDto;
import com.ocom.common.dto.RefreshUserDockDto;
import com.ocom.common.entity.master.EntityMngUserDock;
import com.ocom.common.entity.master.EntityMngUserForm;
import com.ocom.common.entity.master.EntityMngUserInfo;
import com.ocom.common.enums.ExcelDownLoadEnum;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.common.vo.KVSelectedVo;
import com.ocom.human.service.MngUserDockService;
import com.ocom.human.service.MngUserFormService;
import com.ocom.human.service.MngUserInfoService;
import com.ocom.human.service.WechatPerInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Slf4j
@RestController
public class AccountPageController {
    Logger log= LoggerFactory.getLogger(AccountPageController.class);
    @Autowired
    private MngUserInfoService mngUserInfoService;

    @Autowired
    private MngUserFormService mngUserFormService;

    @Autowired
    private WechatPerInfoService wechatPerInfoService;

    @Autowired
    private MngUserDockService mngUserDockService;

    /*
     * @Description:获取管理员用户信息
     * @Author: lu 
     * @Date: 2022/4/18 15:52
     * @param jsonObject:  
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(HumanServiceUrl.URL_GetMngUserInfo)
    public Result getMngUserInfo(@RequestBody JSONObject jsonObject) {
        PageInfo<EntityMngUserInfo> list=mngUserInfoService.selectMngUserInfoList(jsonObject);
        JSONObject reObject=new JSONObject();
        reObject.put("total",list.getTotal());
        reObject.put("list",list.getList());
        return ResultUtil.success(reObject);
    }

    /*
     * @Description: 添加管理员用户信息
     * @Author: lu 
     * @Date: 2022/4/19 11:20
     * @param jsonObject:  
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(HumanServiceUrl.URL_AddMngUserInfo)
    public Result addMngUserInfo(@RequestBody JSONObject jsonObject) {
        log.info("添加管理员用户信息请求参数【{}】",jsonObject);
        if (jsonObject.getLong("comId")==null || jsonObject.getString("userName")==null || jsonObject.getString("password")==null || jsonObject.getInteger("role")==null){
            return ResultUtil.error(ResultEnum.Err_203);
        }
        EntityMngUserInfo entityMngUserInfo=mngUserInfoService.selectUserName(jsonObject.getString("userName"));
        if (entityMngUserInfo!=null){
            return ResultUtil.error(ResultEnum.Err_2008);
        }
        String salt = RandomUtil.getRandomString(30);
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        String password=passwordEncoder.encode(jsonObject.getString("password")+salt);
        EntityMngUserInfo userInfo= JSON.parseObject(jsonObject.toJSONString(),EntityMngUserInfo.class);
        userInfo.setPassword(password);
        userInfo.setSalt(salt);
        Date date=new Date();
        userInfo.setCreateTime(date);
        userInfo.setUpdateTime(date);
        if (mngUserInfoService.insertUserInfoService(userInfo)){
            EntityMngUserInfo entityMngUserInfoTwo=mngUserInfoService.selectUserName(jsonObject.getString("userName"));
            if (entityMngUserInfoTwo==null){
                return ResultUtil.error(ResultEnum.Err_2016);
            }
            JSONObject reObject=new JSONObject();
            reObject.put("comId",entityMngUserInfoTwo.getComId());
            reObject.put("userName",entityMngUserInfoTwo.getUserName());
            reObject.put("id",entityMngUserInfoTwo.getId());
            return ResultUtil.success(reObject);
        }else {
            return ResultUtil.error(ResultEnum.Err_2016);
        }
    }

    /*
     * @Description:更新管理员用户信息
     * @Author: lu 
     * @Date: 2022/4/19 16:51
     * @param jsonObject:  
     * @return: com.ocom.common.resp.Result
     **/
    @PostMapping(HumanServiceUrl.URL_UpdateMngUserInfo)
    public Result UpdateMngUserInfo(@RequestBody JSONObject jsonObject) {
        EntityMngUserInfo entityMngUserInfo=mngUserInfoService.selectUserName(jsonObject.getString("userName"));
        if (entityMngUserInfo!=null){
         
            if (!entityMngUserInfo.getId().equals(jsonObject.getLong("id"))){
                return ResultUtil.error(ResultEnum.Err_2008);
            }
        }
        EntityMngUserInfo userInfo= JSON.parseObject(jsonObject.toJSONString(),EntityMngUserInfo.class);
        if (jsonObject.getString("password")!=null){
            String salt = RandomUtil.getRandomString(30);
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String password=passwordEncoder.encode(jsonObject.getString("password")+salt);
            userInfo.setPassword(password);
            userInfo.setSalt(salt);
        }
        userInfo.setUpdateTime(new Date());
        if (mngUserInfoService.UpdateUserInfoService(userInfo)){
            EntityMngUserInfo entityMngUserInfoTwo=mngUserInfoService.selectUserName(jsonObject.getString("userName"));
            if (entityMngUserInfoTwo==null){
                return ResultUtil.error(ResultEnum.Err_3026);
            }
            JSONObject reObject=new JSONObject();
            reObject.put("comId",entityMngUserInfoTwo.getComId());
            reObject.put("userName",entityMngUserInfoTwo.getUserName());
            reObject.put("id",entityMngUserInfoTwo.getId());
            return ResultUtil.success(reObject);
        }else {
            return ResultUtil.error(ResultEnum.Err_3026);
        }
    }

    @PostMapping(HumanServiceUrl.URL_DeleteMngUserInfo)
    public Result deleteMngUserInfo(@RequestBody JSONObject jsonObject) {
        if (mngUserInfoService.deleteMngUserInfo(jsonObject)<=0){
            return ResultUtil.error(ResultEnum.Err_3016);
        }
        wechatPerInfoService.removePerson(jsonObject.getLong("comId"),jsonObject.getLong("id"));
        return ResultUtil.success(jsonObject);
    }

    @PostMapping(HumanServiceUrl.URL_GetMngUserForm)
    public Result getMngUserFormSelected(@RequestBody GetMngUserFormDto dto){

        EntityMngUserForm entityMngUserForm = mngUserFormService.findByUserIdAndPageAndType(dto.getUserId(),dto.getPage(),dto.getType());

        List<KVSelectedVo> newEnums = new ArrayList<>();

        if (null == entityMngUserForm) {
            newEnums = ExcelDownLoadEnum.getValueByKey(dto.getPage());
        } else {

            List<Integer> form = JSONObject.parseArray(entityMngUserForm.getForm(), Integer.class);
            List<KVSelectedVo> enums = ExcelDownLoadEnum.getValueByKey(entityMngUserForm.getPage());
            enums = enums.stream().map(o -> {o.setSelect(false);return o;}).collect(Collectors.toList());
            for (Integer key : form) {
                enums.stream().filter(o -> key.equals(o.getKey())).forEach(o -> o.setSelect(true));
            }
            for (Integer key : form) {
                newEnums.add(enums.get(key));
            }
            newEnums = Stream.of(newEnums, enums).flatMap(Collection::stream).distinct().collect(Collectors.toList());
        }

        return ResultUtil.success(newEnums);
    }

    @PostMapping(HumanServiceUrl.URL_EditMngUserForm)
    public Result editMngUserFormSelected(@RequestBody EditMngUserFormDto dto){
        if (null == dto.getForm() || 0 == dto.getForm().size()) {
            mngUserFormService.deleteByUserIdAndPageAndType(dto.getUserId(),dto.getPage(),dto.getType());
        } else {
            EntityMngUserForm entityMngUserForm = mngUserFormService.findByUserIdAndPageAndType(dto.getUserId(),dto.getPage(),dto.getType());
            if (null == entityMngUserForm) {
                entityMngUserForm = new EntityMngUserForm();
                entityMngUserForm.setForm(JSON.toJSONString(dto.getForm()));
                entityMngUserForm.setUserId(dto.getUserId());
                entityMngUserForm.setPage(dto.getPage());
                entityMngUserForm.setType(dto.getType());
                mngUserFormService.save(entityMngUserForm);
            } else {
                entityMngUserForm.setForm(JSON.toJSONString(dto.getForm()));
                mngUserFormService.updateById(entityMngUserForm);
            }
        }

        return ResultUtil.success();
    }

    @PostMapping(HumanServiceUrl.URL_RefreshUserDock)
    public Result refreshUserDock(@RequestBody RefreshUserDockDto request){
        EntityMngUserDock entityMngUserDock = mngUserDockService.findByComIdAndUserIdAndDockCode(request.getComId(), request.getUserId(), request.getDockCode());
        if (StringUtils.isBlank(request.getUserName()) && null != entityMngUserDock) {
            mngUserDockService.removeById(entityMngUserDock.getId());
        } else {
            if (null == entityMngUserDock) {
                entityMngUserDock = new EntityMngUserDock();
                entityMngUserDock.setComId(request.getComId());
                entityMngUserDock.setUserId(request.getUserId());
                entityMngUserDock.setDockCode(request.getDockCode());
            }
            entityMngUserDock.setUserName(request.getUserName());
            entityMngUserDock.setPassword(request.getPassword());
            mngUserDockService.saveOrUpdate(entityMngUserDock);
        }
        return ResultUtil.success();

    }


    @PostMapping(HumanServiceUrl.URL_getMngUserInfoById)
    public Result getMngUserInfoById(Integer userId) {
        if (userId == null || userId <= 0) {
            return ResultUtil.error(ResultEnum.Err_303);
        }
        EntityMngUserInfo entityMngUserInfo = mngUserInfoService.selectUserById(userId);
        if(entityMngUserInfo==null){
            return ResultUtil.error(ResultEnum.Err_303);
        }
        return ResultUtil.success(entityMngUserInfo);
    }
}
